package org.example.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.pojo.DItem;
import org.example.pojo.DLeave;
import org.example.pojo.select.DLeaveSelect;
import org.example.service.DLeaveService;
import org.example.mapper.DLeaveMapper;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author chenhongkai
* @description 针对表【d_leave(请假记录表)】的数据库操作Service实现
* @createDate 2024-08-05 17:06:47
*/
@Service
public class DLeaveServiceImpl extends ServiceImpl<DLeaveMapper, DLeave>
    implements DLeaveService{

    @Autowired
    private DLeaveMapper dLeaveMapper;

    @Override
    public Result<Map> SelectLeaves(DLeaveSelect dLeaveSelect) {

        //格式化日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if(dLeaveSelect.getLeaveStartDate() != null && !dLeaveSelect.getLeaveStartDate().isEmpty()){
            Instant instantStart = Instant.parse(dLeaveSelect.getLeaveStartDate());
            String formattedDateDirectStart = instantStart.atZone(ZoneId.of("Asia/Shanghai")).toLocalDate().format(formatter);
            dLeaveSelect.setLeaveStartDate(formattedDateDirectStart);
        }
        if(dLeaveSelect.getLeaveEndDate() != null && !dLeaveSelect.getLeaveEndDate().isEmpty()){
            Instant instantEnd = Instant.parse(dLeaveSelect.getLeaveEndDate());
            String formattedDateDirectEnd = instantEnd.atZone(ZoneId.of("Asia/Shanghai")).toLocalDate().format(formatter);
            dLeaveSelect.setLeaveEndDate(formattedDateDirectEnd);
        }

        Page<DItem> page = new Page<>(dLeaveSelect.getCurrentPage(),dLeaveSelect.getPageSize());
        page.setSearchCount(false);

        Integer leavesTotal = dLeaveMapper.SelectLeavesTotal(dLeaveSelect);
        page.setTotal(leavesTotal);

        IPage<Map> mapIPage = dLeaveMapper.SelectLeaves(page,dLeaveSelect);

        Map leaveMap = new HashMap<>();

        leaveMap.put("pageSize",mapIPage.getSize());
        leaveMap.put("pageTotal",mapIPage.getTotal());
        leaveMap.put("leaveData",mapIPage.getRecords());

        return Result.ok(leaveMap);
    }

    @Override
    public Result<Map> AddLeave(List<DLeaveSelect> dLeaveList) {
        for(DLeaveSelect dLeaveSelect : dLeaveList){
            dLeaveMapper.insertLeave(dLeaveSelect);
        }
        return Result.ok(null);

    }

    @Override
    public Result<Map> DeleteLeave(List<DLeave> dLeaveList) {
        for(DLeave dLeave : dLeaveList){
            dLeaveMapper.deleteLeave(dLeave);
        }
        return Result.ok(null);
    }
}




